<template>
  <div id="questionsView">
    <!-- 搜索区域 -->
    <a-card class="search-card" :bordered="true">
      <template #title>
        <div class="card-title">
          <icon-filter />
          <span>筛选条件</span>
        </div>
      </template>
      <a-form :model="searchParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              field="title"
              label="题目名称"
              tooltip="请输入题目的名称"
            >
              <a-input
                v-model="searchParams.title"
                placeholder="请输入要搜索的题目名称"
                allow-clear
              />
            </a-form-item>
          </a-col>

          <a-col :span="8">
            <a-form-item field="tags" label="题目标签">
              <a-select
                v-model="selectedTag"
                placeholder="选择题目类型"
                allow-clear
                @change="handleTagChange"
              >
                <a-option value="算法">算法</a-option>
                <a-option value="数据库">数据库</a-option>
                <a-option value="前端">前端</a-option>
                <a-option value="后端">后端</a-option>
                <a-option value="测试">测试</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="4" style="display: flex; align-items: flex-end">
            <a-button type="primary" @click="doSubmit" status="success">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 题目列表 -->
    <a-card class="table-card" :bordered="true">
      <template #title>
        <div class="card-title">
          <icon-code-square />
          <span>题目列表</span>
        </div>
      </template>

      <a-table
        :ref="tableRef"
        :columns="columns"
        :data="dataList"
        :loading="tableLoading"
        row-key="id"
        :pagination="{
          showTotal: true,
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total,
          position: ['bottomCenter'],
        }"
        :row-class-name="
          (_record: any, index: number) => (index % 2 === 0 ? 'even-row' : 'odd-row')
        "
        @page-change="onPageChange"
      >
        <template #id="{ record }">
          <span class="question-id">#{{ record.id }}</span>
        </template>

        <template #title="{ record }">
          <div class="question-title">
            <a-tooltip position="right" content="点击查看题目详情">
              <a @click="toQuestionPage(record)" class="question-link">
                {{ record.title }}
              </a>
            </a-tooltip>
          </div>
        </template>

        <template #tags="{ record }">
          <a-space wrap>
            <a-tag
              v-for="(tag, index) of record.tags"
              :key="index"
              :color="handleColor(record.tags[index])"
            >
              {{ tag }}
            </a-tag>
          </a-space>
        </template>

        <template #acceptedRate="{ record }">
          <div class="acceptance-rate">
            <a-progress
              :percent="calculateAcceptanceRate(record) / 100"
              :stroke-color="getAcceptanceRateColor(record)"
              :show-text="false"
              style="width: 100%"
            />
            <div class="rate-text">{{ calculateAcceptanceRate(record) }}%</div>
          </div>
        </template>

        <template #createTime="{ record }">
          <div class="time-cell">
            {{ moment(record.createTime).format("YYYY-MM-DD") }}
          </div>
        </template>

        <template #optional="{ record }">
          <a-space>
            <a-button
              type="primary"
              size="small"
              @click="toQuestionPage(record)"
            >
              <template #icon><icon-edit /></template>
              做题
            </a-button>
          </a-space>
        </template>

        <template #empty>
          <div class="empty-state">
            <icon-empty />
            <p>暂无题目数据</p>
          </div>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import {
  Page_Question_,
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import * as querystring from "querystring";
import { useRouter } from "vue-router";
import moment from "moment";
import {
  IconFilter,
  IconSearch,
  IconRefresh,
  IconEdit,
  IconEmpty,
  IconCodeSquare,
} from "@arco-design/web-vue/es/icon";

const tableRef = ref();
const dataList = ref([]);
const total = ref(0);
const tableLoading = ref(false);

const searchParams = ref<QuestionQueryRequest>({
  title: "",
  tags: [],
  pageSize: 8,
  current: 1,
});

const selectedTag = ref("");

const handleTagChange = (value: string) => {
  searchParams.value.tags = value ? [value] : [];
};

const loadData = async () => {
  tableLoading.value = true;
  try {
    const res = await QuestionControllerService.listQuestionVoByPageUsingPost(
      searchParams.value
    );
    if (res.code === 0) {
      dataList.value = res.data.records;
      total.value = res.data.total;
    } else {
      message.error("加载失败，" + res.message);
    }
  } catch (error) {
    message.error("请求失败，请检查网络");
  } finally {
    tableLoading.value = false;
  }
};

/**
 * 计算通过率
 */
const calculateAcceptanceRate = (record: any): number => {
  if (!record.submitNum) {
    return 0;
  }
  return Number(((record.acceptedNum / record.submitNum) * 100).toFixed(1));
};

/**
 * 根据通过率返回不同颜色
 */
const getAcceptanceRateColor = (record: any): string => {
  const rate = calculateAcceptanceRate(record);
  if (rate < 30) return "#f56c6c";
  if (rate < 60) return "#e6a23c";
  return "#67c23a";
};

/**
 * 处理不同难度标签对应不同的颜色
 * @param record
 */
const handleColor = (record: any): string => {
  if (record === "算法") {
    return "#FFB6C1"; // 浅粉色
  } else if (record === "数据库") {
    return "#98FB98"; // 浅绿色
  } else if (record === "前端") {
    return "#87CEEB"; // 天蓝色
  } else if (record === "后端") {
    return "#FFD700"; // 浅金色
  } else if (record === "测试") {
    return "#DDA0DD"; // 浅紫色
  } else {
    return "#D3D3D3"; // 浅灰色
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

const columns = [
  {
    title: "题号",
    dataIndex: "id",
    slotName: "id",
    width: 200,
    align: "center",
  },
  {
    title: "题目名称",
    dataIndex: "title",
    slotName: "title",
    width: 200,
  },
  {
    title: "标签",
    slotName: "tags",
    align: "center",
    width: 150,
  },
  {
    title: "通过率",
    slotName: "acceptedRate",
    align: "center",
    width: 150,
  },
  {
    title: "创建时间",
    slotName: "createTime",
    align: "center",
    width: 150,
  },
  {
    title: "操作",
    slotName: "optional",
    align: "center",
    width: 150,
  },
];

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

// 重置所有筛选条件
const resetFilters = () => {
  searchParams.value = {
    title: "",
    tags: [],
    pageSize: 8,
    current: 1,
  };
  selectedTag.value = "";
  loadData();
};

const router = useRouter();

/**
 * 跳转到做题页面
 * @param question
 */
const toQuestionPage = (question: Question) => {
  router.push({
    path: `/view/question/${question.id}`,
  });
};

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
  loadData();
};
</script>

<style scoped>
#questionsView {
  max-width: 1600px;
  margin: 0 auto;
  padding: 30px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-title {
  margin: 0;
  font-size: 28px;
  color: #333;
  font-weight: 600;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #165dff;
  font-weight: 500;
  font-size: 18px;
}

.search-card,
.table-card {
  margin-bottom: 30px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  padding: 5px;
}

/* 增加表单元素尺寸 */
:deep(.arco-form-item) {
  margin-bottom: 20px;
}

:deep(.arco-input),
:deep(.arco-select) {
  height: 40px;
  font-size: 15px;
}

:deep(.arco-btn) {
  height: 40px;
  padding: 0 20px;
  font-size: 15px;
}

/* 表格样式 */
:deep(.arco-table-th) {
  padding: 16px 12px;
  font-size: 16px;
}

:deep(.arco-table-td) {
  padding: 14px 12px;
  font-size: 15px;
}

:deep(.even-row) {
  background-color: #f9f9f9;
}

:deep(.odd-row) {
  background-color: #ffffff;
}

.question-id {
  font-family: "Courier New", monospace;
  font-weight: 600;
  color: #165dff;
  font-size: 15px;
}

.question-title {
  font-weight: 500;
  font-size: 16px;
}

.acceptance-rate {
  width: 100%;
}

.rate-text {
  text-align: center;
  font-size: 12px;
  margin-top: 4px;
  color: #666;
}

.time-cell {
  white-space: nowrap;
  color: #666;
  font-family: Monaco, monospace;
  font-size: 12px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #86909c;
}

.empty-state :deep(svg) {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c2c7d0;
}

.empty-state p {
  margin-bottom: 16px;
}

.question-link {
  color: #333;
  transition: color 0.3s;
  text-decoration: none;
  font-size: 16px;
}

.question-link:hover {
  color: #165dff;
  text-decoration: underline;
}
</style>
